package com.hcj.testThreadPool;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: HuangChangjin 2017-12-05 18:45
 * @Description: 线程池构造工程
 */
public class ExecutorServiceFactory {
    private static ExecutorServiceFactory executorServiceFactory = new ExecutorServiceFactory();
    public ExecutorServiceFactory(){

    }
    // 线程池
    private ExecutorService executorService;

    // 获取构造工厂
    public static ExecutorServiceFactory getInstance(){
        return executorServiceFactory;
    }

    /**
     * 获取线程池工厂
     *
     * @return
     */
    private ThreadFactory getThreadFactory() {
        return new ThreadFactory() {
            AtomicInteger sn = new AtomicInteger();
            public Thread newThread(Runnable r) {
                SecurityManager s = System.getSecurityManager();
                ThreadGroup group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
                Thread t = new Thread(group, r);
                t.setName("任务线程 - " + sn.incrementAndGet());
                return t;
            }
        };
    }

    /** 可计划的线程池 */
    public ExecutorService createScheduledThreadPool(){
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        executorService = Executors.newScheduledThreadPool(10 * availableProcessors, getThreadFactory());
        return executorService;
    }
    /** 单个线程池 */
    public ExecutorService createSingleThreadPool(){
        executorService = Executors.newSingleThreadExecutor(getThreadFactory());
        return executorService;
    }
    /** 可缓存的线程池 */
    public ExecutorService createCachedThreadPool(){
        executorService = Executors.newCachedThreadPool(getThreadFactory());
        return executorService;
    }
    /** 固定的线程池 */
    public ExecutorService createFixedThreadPool(int count){
        executorService = Executors.newFixedThreadPool(count,getThreadFactory());
        return executorService;
    }

}
